package com.navidove.web.vo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.navidove.commons.vo.Paging;

public class JqGridPaging implements Paging {

    private static final long serialVersionUID = -2887762018156751489L;
    
    private int page = 1;
    private int rows;
    private int fullSize;
    private String sort;
    private String dir;

    public int getPage() {
        return page;
    }
    
    public void setPage(int page) {
        this.page = page;
    }
    
    public String getSidx() {
        return sort;
    }

    public void setSidx(String sidx) {
        this.sort = sidx;
    }

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }
    

    public String getSord() {
        return dir;
    }

    public void setSord(String sord) {
        this.dir = sord;
    }

    public String getDir() {
        return dir;
    }

    public void setDir(String dir) {
        this.dir = dir;
    }

    public int getObjectsPerPage() {
        return rows;
    }

    public void setObjectsPerPage(int objectsPerPage) {
        setRows(objectsPerPage);
    }
    
    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    @Override
    public int getFirstResult() {
        return (this.page - 1) * this.rows;
    }

    @Override
    public boolean isAsc() {
        return "asc".equalsIgnoreCase(this.dir);
    }

    public void setAsc(boolean isAsc) {
        this.dir = isAsc ? "asc" : "desc";
    }

    public int getFullSize() {
        return fullSize;
    }

    public void setFullSize(int fullSize) {
        this.fullSize = fullSize;
    }
    
    public int getTotalPageSize() {
        if (this.getFullSize() == 0) return 0;
        return (int) (this.getFullSize() / this.getObjectsPerPage())  + (this.getFullSize() % this.getObjectsPerPage() > 0 ? 1 : 0);
        
    }
    
    public Map<String, Object> convert(List<?> results) {
        Map<String, Object> rtnVal = new HashMap<String, Object>();
        rtnVal.put("page", getPage());
        rtnVal.put("total", getTotalPageSize());
        rtnVal.put("records", getFullSize());
        rtnVal.put("rows", results);
        return rtnVal;
    }

	public Map<String, String> getOrder() {
		Map<String, String> map = new HashMap<String, String>();
		if (StringUtils.isNotBlank(getSort())) {
			map.put(getSort(), getDir());
		}
		return map;
	}
}
